package cn.gcjxsc.payment.util;

import org.apache.commons.codec.digest.DigestUtils;

import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

/**
 * @author pumbaa
 * @since 1.0
 */
public class WxUtil {
    public static final String SING_TYPE = "MD5";
    //统一下单
    public static final String URI_PAY_ORDER = "https://api.mch.weixin.qq.com/pay/unifiedorder";
    //关闭交易订单
    public static final String URI_CLOSE_ORDER = "https://api.mch.weixin.qq.com/pay/closeorder";
    //查询交易订单
    public static final String URI_QUERY_ORDER = "https://api.mch.weixin.qq.com/pay/orderquery";
    //发红包
    public static final String URI_SEND_RED_PACK = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
    //查询红包信息
    public static final String URI_QUERY_RED_PACK = "https://api.mch.weixin.qq.com/mmpaymkttransfers/gethbinfo";

    public static final String SUCCESS = "SUCCESS";
    public static final String FAIL = "FAIL";
    public static final String NOTPAY = "NOTPAY";

    public static final String MD5 = "MD5";
    public static final String TRADE_TYPE_JS = "JSAPI";

    /**
     * 获取随机字符串 Nonce Str
     *
     * @return String 随机字符串
     */
    public static String generateNonceStr() {
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
    }

    /**
     * 生成签名. 注意，若含有sign_type字段，必须和signType参数保持一致。
     *
     * @param data     待签名数据
     * @param key      API密钥
     * @return 签名
     */
    public static String generateSignature(final Map<String, String> data, String key) {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            if (k.equals("sign")) {
                continue;
            }
            if (data.get(k).trim().length() > 0) {
                sb.append(k).append("=").append(data.get(k).trim()).append("&");
            }
        }
        sb.append("key=").append(key);
        byte[] bytes = sb.toString().getBytes(Charset.forName("utf-8"));
        return DigestUtils.md5Hex(bytes).toUpperCase();
    }
}
